import sys
from PyQt5.QtWidgets import QApplication, QWidget, QVBoxLayout, QHBoxLayout, QTextEdit, QPushButton

from config import read_config
from tcp import tcp_client


class ChatApp(QWidget):
    def __init__(self):
        super().__init__()

        self.initUI()

    def initUI(self):
        self.setWindowTitle('OpenAi 3.0')
        self.setGeometry(100, 100, 800, 600)

        # 创建对话框
        self.dialog_box = QTextEdit(self)
        self.dialog_box.setReadOnly(True)

        # 创建输入框和发送按钮
        self.input_box = QTextEdit(self)
        self.send_button = QPushButton('send', self)
        self.send_button.clicked.connect(self.sendMessage)

        self.clear_button = QPushButton('clear', self)
        self.clear_button.clicked.connect(self.clearDialog)

        # 创建布局
        vbox = QVBoxLayout()
        vbox.addWidget(self.dialog_box)
        hbox = QHBoxLayout()
        hbox.addWidget(self.input_box)
        hbox.addWidget(self.send_button)
        vbox.addLayout(hbox)

        self.setLayout(vbox)

    def sendMessage(self):
        message = self.input_box.toPlainText()
        if message:
            self.dialog_box.append("You: " + message)
            # 在这里发送消息到聊天机器人并处理响应
            config = read_config()
            response = tcp_client(message,config['server_host'],config['server_port'],config['password'])
            # 在示例中，我们简单地回显用户输入
            self.dialog_box.append("OpenAi 3.0: " + response)
        # 清空输入框
        self.input_box.clear()

    def clearDialog(self):
        # 清空对话框内容
        self.dialog_box.clear()

if __name__ == '__main__':
    app = QApplication(sys.argv)
    chat_app = ChatApp()
    chat_app.show()
    sys.exit(app.exec_())
